package Controller;

import Services.WebService;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseHttpServlet extends HttpServlet{
    protected void processRequest(HttpServletRequest request, HttpServletResponse response, WebService webServices, String action) throws ServletException, IOException {}
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	WebService webServices = new WebService();
    	webServices.init(request);
        String action = request.getParameter("action");
        
        if(this.checkPrivilege(webServices))
            this.processRequest(request, response, webServices, action);
        else
            this.ifPermissionDenied(response, webServices);
        webServices.clearUp();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	WebService webServices = new WebService();
    	webServices.init(request);
        String action = request.getParameter("action");
        
        if(this.checkPrivilege(webServices))
            this.processRequest(request, response, webServices, action);
        else
            this.ifPermissionDenied(response, webServices);
        webServices.clearUp();
    }

    protected boolean checkPrivilege(WebService webServices) {
        //Basically no permission checking by default
        return true;
    }

    protected void ifPermissionDenied(HttpServletResponse response, WebService webServices) throws IOException {
    	response.sendRedirect(webServices.getBaseURL()+"/login");
    }
    
    protected void forward(HttpServletRequest request, HttpServletResponse response, WebService webServices, String action, String jspAddr){
    	request.setAttribute("currentUser", webServices.getCurrentUser());
    	request.setAttribute("baseURL", webServices.getBaseURL());
    	request.setAttribute("action", action);
    	
    	System.out.println("Page rendering: "+jspAddr);
    	RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher(jspAddr);
		try {
			dispatcher.forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
    }
}